﻿using IniParser;
using IniParser.Model;
using Microsoft.AspNet.SignalR;
using SignalR_ChatRoom_Server.DBM;
using SignalR_ChatRoom_Server.Model.Entities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalR_ChatRoom_Server
{
    public class ChatHub:Hub
    {
        private static ConcurrentDictionary<int, Users> CurrentClients = new ConcurrentDictionary<int, Users>();

        private IniData _data;
        public ChatHub()
        {
            var parser = new FileIniDataParser();
            _data = parser.ReadFile("Configs\\settings.ini");
        }
        public int Register(Users request)
        {
            var context = DbContext.MainContext;
            var maxID = context.Queryable<IDRecord>().Max(it => it.LoginID);
            int distributeID = maxID + 1;
            var succeed = context.Insertable<IDRecord>(new IDRecord {LoginID = distributeID }).ExecuteCommand();
            var succeed2 = context.Insertable<Users>(request).ExecuteCommand();
            return distributeID;
        }

        public List<Users> Login(int loginID,string password)
        {
            var context = DbContext.MainContext;
            var result = context.Queryable<Users>().Where(it => it.LoginID == loginID && it.Password == password).First();
            if(result != null)
            {
                if(CurrentClients.Keys.Contains(result.LoginID))
                {
                    return CurrentClients.Values.ToList();
                }
                else
                {
                    CurrentClients.TryAdd(result.LoginID,result);
                    return CurrentClients.Values.ToList();
                }
            }
            return null;
        }
    }
}
